package lolxxs.chenyanting.service.impl;


import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import lolxxs.chenyanting.model.Todo;
import lolxxs.chenyanting.mapper.TodoMapper;
import lolxxs.chenyanting.service.ITodoService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import lolxxs.chenyanting.utils.IdWorker;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.Date;
import java.util.List;

/**
 * <p>
 *  服务实现类
 * </p>
 *
 * @since 2021-12-30
 */
@Service
public class TodoServiceImpl extends ServiceImpl<TodoMapper, Todo> implements ITodoService {
    @Autowired
    private TodoMapper todoMapper;

    @Autowired
    private IdWorker idWorker;

    @Override
    public int add(Todo todo) {
        Date date = new Date();
        todo.setTodoId(idWorker.nextId());
        todo.setCreateTime(date);
        todo.setUpdateTime(date);
        todo.setState(1);
        return todoMapper.insert(todo);
    }

    @Override
    public int update(Todo todo) {
        todo.setUpdateTime(new Date());
        return todoMapper.updateById(todo);
    }

    @Override
    public List<Todo> query(Todo todo) {
        List<Todo> todos = todoMapper.selectList(queryWrapper(todo));
        if (todos.size() > 0) {
            return todos;
        }
        return null;
    }

    @Override
    public int delete(Todo todo) {
        Todo todo1 = new Todo();
        todo1.setState(0);
        todo1.setUpdateTime(new Date());
        return todoMapper.update(todo1, queryWrapper(todo));
    }

    private QueryWrapper<Todo> queryWrapper(Todo todo) {
        QueryWrapper<Todo> wrapper=new QueryWrapper<>();
        if (todo.getTodoId() != null) {
            wrapper.eq("todoId", todo.getTodoId());
        }
        if (todo.getUserId() != null) {
            wrapper.eq("userId", todo.getUserId());
        }
        if (todo.getTodoDescription() != null) {
            wrapper.like("todoDescription", todo.getTodoDescription());
        }
        if (todo.getState() != null) {
            wrapper.eq("state", todo.getState());
        }
        if (todo.getCreateTime() != null) {
            // 大于左边时间
            wrapper.ge("createTime", todo.getCreateTime());
        }
        if (todo.getUpdateTime() != null) {
            // 小于右边时间
            wrapper.le("createTime", todo.getUpdateTime());
        }
        return wrapper;
    }
}
